import { loginDoctor, getInfoDoctor, loginPatient, getInfoPatient } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const roleMap = {
  doctor: ['doctor'],
  patient: ['patient'],
  medicine: ['medicine']
}

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  roleSelected: '' // 登录时选择的角色
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROLESELECTER: (state, roleSelected) => {
    state.roleSelected = roleSelected
  }
}

const actions = {
  // user login
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       const { data } = response
  //       commit('SET_TOKEN', data.token)
  //       setToken(data.token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  // 医生登录
  loginDoctor({ commit }, userInfo) {
    const { phone, password } = userInfo
    return new Promise((resolve, reject) => {
      loginDoctor({ doctor_account: phone.trim(), doctor_password: password }).then(response => {
        const data = response
        // 保存token和角色
        commit('SET_TOKEN', data.refresh_token)
        commit('SET_ROLESELECTER', 'doctor')
        setToken(data.refresh_token)
        localStorage.setItem('token', data.refresh_token)
        localStorage.setItem('roleSelected', 'doctor')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 病人登录
  loginPatient({ commit }, userInfo) {
    const { phone, password } = userInfo
    return new Promise((resolve, reject) => {
      loginPatient({ phone: phone.trim(), password: password }).then(response => {
        const data = response
        commit('SET_TOKEN', data.refresh_token)
        commit('SET_ROLESELECTER', 'patient')
        setToken(data.refresh_token)
        localStorage.setItem('token', data.refresh_token)
        localStorage.setItem('roleSelected', 'patient')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 药房登录
  loginMedicine({ commit }, userInfo) {
    const { phone, password } = userInfo
    return new Promise((resolve, reject) => {
      loginDoctor({ doctor_account: phone.trim(), doctor_password: password }).then(response => {
        const data = response
        // 保存token和角色
        commit('SET_TOKEN', data.refresh_token)
        commit('SET_ROLESELECTER', 'medicine')
        setToken(data.refresh_token)
        localStorage.setItem('token', data.refresh_token)
        localStorage.setItem('roleSelected', 'medicine')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 医生登录获取个人信息
  getInfoDoctor({ commit }) {
    return new Promise((resolve, reject) => {
      getInfoDoctor({ token: localStorage.getItem('token') }).then(response => {
        const data = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const data1 = Object.assign({}, { roles: roleMap['doctor'], name: 'name', avatar: 'avatar', introduction: 'introduction' })
        // const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!data1.roles || data1.roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        // 可在此全局设置需要保存的用户信息
        commit('SET_ROLES', data1.roles)
        commit('SET_NAME', data1.name)
        commit('SET_AVATAR', data1.avatar)
        commit('SET_INTRODUCTION', data1.introduction)
        localStorage.setItem('User', JSON.stringify(data))
        localStorage.setItem('dImg', JSON.stringify(data.photo))
        localStorage.setItem('presentUser', JSON.stringify(data))
        resolve(data1)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 药房登录获取个人信息
  getInfoMedicine({ commit }) {
    return new Promise((resolve, reject) => {
      getInfoDoctor({ token: localStorage.getItem('token') }).then(response => {
        const data = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const data1 = Object.assign({}, { roles: roleMap['medicine'], name: 'name', avatar: 'avatar', introduction: 'introduction' })
        // const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!data1.roles || data1.roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        // 可在此全局设置需要保存的用户信息
        commit('SET_ROLES', data1.roles)
        commit('SET_NAME', data1.name)
        commit('SET_AVATAR', data1.avatar)
        commit('SET_INTRODUCTION', data1.introduction)
        localStorage.setItem('User', JSON.stringify(data))
        localStorage.setItem('presentUser', JSON.stringify(data))
        resolve(data1)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 病人登录获取个人信息
  getInfoPatient({ commit }) {
    return new Promise((resolve, reject) => {
      getInfoPatient({ token: localStorage.getItem('token') }).then(response => {
        const data = response
        console.log(data)
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const data1 = Object.assign({}, { roles: roleMap['patient'], name: 'name', avatar: 'avatar', introduction: 'introduction' })
        // const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!data1.roles || data1.roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', data1.roles)
        commit('SET_NAME', data1.name)
        commit('SET_AVATAR', data1.avatar)
        commit('SET_INTRODUCTION', data1.introduction)
        localStorage.setItem('presentUser', JSON.stringify(data))
        // const presentUser = JSON.parse(localStorage.getItem('presentUser'))
        // console.log(presentUser.user_id)
        // console.log(presentUser.name)
        // console.log(presentUser)

        localStorage.setItem('user_id', data.user_id) // 保存病人id
        resolve(data1)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      //   commit('SET_TOKEN', '')
      //   commit('SET_ROLES', [])
      //   removeToken()
      //   resetRouter()

      //   // reset visited views and cached views
      //   // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      //   dispatch('tagsView/delAllViews', null, { root: true })

      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      localStorage.clear()
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      localStorage.clear()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
